#include <sfud.h>
#include <stdarg.h>
#include "gd32f30x.h"
typedef struct {
    uint32_t spix;
    uint32_t cs_gpiox;
    uint32_t cs_gpio_pin;
} spi_user_data, *spi_user_data_t;
static spi_user_data spi1 = { .spix = SPI1, .cs_gpiox = GPIOE, .cs_gpio_pin = GPIO_PIN_2 };

// 片选控制宏
#define SPI1_CS_SELECT()  	gpio_bit_write(spi1.cs_gpiox, spi1.cs_gpio_pin, RESET);  // 低电平选中
#define SPI1_CS_DESELECT()  gpio_bit_write(spi1.cs_gpiox, spi1.cs_gpio_pin, SET);    // 高电平取消

static void rcc_configuration(spi_user_data_t spi) {
    if (SPI1 == spi->spix) {
        rcu_periph_clock_enable(RCU_SPI1);			// spi
        rcu_periph_clock_enable(RCU_GPIOB); // scl mosi miso
        rcu_periph_clock_enable(RCU_GPIOE); // cs
    } else if (SPI2== spi->spix) {
        /* you can add SPI2 code here */
    }
}

static void gpio_configuration(spi_user_data_t spi) {
    if (spi->spix == SPI1) {
        /* SCK:PB13  MISO:PB14  MOSI:PB15 */
        gpio_init(GPIOB, GPIO_MODE_AF_PP, GPIO_OSPEED_50MHZ, GPIO_PIN_13|GPIO_PIN_15);
        gpio_init(GPIOB, GPIO_MODE_IPU, GPIO_OSPEED_50MHZ, GPIO_PIN_14);
        /* CS: PE2 */
        gpio_init(spi1.cs_gpiox, GPIO_MODE_OUT_PP, GPIO_OSPEED_50MHZ, spi1.cs_gpio_pin);
    } else if (spi->spix == SPI2) {
        /* you can add SPI2 code here */
    }
}

static void spi_configuration(spi_user_data_t spi) {
    spi_parameter_struct spiInitStruct;
    spi_struct_para_init(&spiInitStruct);
    //全双工 接受和发送在同一个周期
    spiInitStruct.trans_mode = SPI_TRANSMODE_FULLDUPLEX;
    // 主机
    spiInitStruct.device_mode = SPI_MASTER;
    // 8bit
    spiInitStruct.frame_size = SPI_FRAMESIZE_8BIT;
    /// Mode 0 (CPOL=0, CPHA=0)
    spiInitStruct.clock_polarity_phase = SPI_CK_PL_LOW_PH_1EDGE;
    // 软件控制片选
    spiInitStruct.nss = SPI_NSS_SOFT;
    // 二分频
    spiInitStruct.prescale = SPI_PSC_2;
    // 高位优先
    spiInitStruct.endian = SPI_ENDIAN_MSB;
    spi_init(spi->spix, &spiInitStruct);
    spi_enable(spi->spix);
}

static void spi_lock(const sfud_spi *spi) {
    __disable_irq();
}

static void spi_unlock(const sfud_spi *spi) {
    __enable_irq();
}

static char log_buf[256];

void sfud_log_debug(const char* file, const long line, const char* format, ...);
/**
 * SPI write data then read data
 */
static sfud_err spi_write_read(const sfud_spi *spi, const uint8_t *write_buf, size_t write_size, uint8_t *read_buf,
                               size_t read_size) {
    sfud_err result = SFUD_SUCCESS;
    uint8_t send_data, read_data;
    spi_user_data_t spi_dev = (spi_user_data_t) spi->user_data;

    if (write_size) {
        SFUD_ASSERT(write_buf);
    }
    if (read_size) {
        SFUD_ASSERT(read_buf);
    }

    SPI1_CS_SELECT();
    /* 开始读写数据 */
    for (size_t i = 0, retry_times; i < write_size + read_size; i++) {
        /* 先写缓冲区中的数据到 SPI 总线，数据写完后，再写 dummy(0xFF) 到 SPI 总线 */
        if (i < write_size) {
            send_data = *write_buf++;
        } else {
            send_data = SFUD_DUMMY_DATA;
        }
        /* 发送数据 */
        retry_times = 1000;
        while (spi_i2s_flag_get(spi_dev->spix, SPI_FLAG_TBE) == RESET) {
            SFUD_RETRY_PROCESS(NULL, retry_times, result);
        }
        if (result != SFUD_SUCCESS) {
            goto exit;
        }
        spi_i2s_data_transmit(spi_dev->spix, send_data);
        /* 接收数据 */
        retry_times = 1000;
        while (spi_i2s_flag_get(spi_dev->spix, SPI_FLAG_RBNE) == RESET) {
            SFUD_RETRY_PROCESS(NULL, retry_times, result);
        }
        if (result != SFUD_SUCCESS) {
            goto exit;
        }
        read_data = spi_i2s_data_receive(spi_dev->spix);
        /* 写缓冲区中的数据发完后，再读取 SPI 总线中的数据到读缓冲区 */
        if (i >= write_size) {
            *read_buf++ = read_data;
        }
    }
exit:
    SPI1_CS_DESELECT();
    return result;
}

#ifdef SFUD_USING_QSPI
/**
 * read flash data by QSPI
 */
static sfud_err qspi_read(const struct __sfud_spi* spi, uint32_t addr, sfud_qspi_read_cmd_format* qspi_read_cmd_format,
                          uint8_t* read_buf, size_t read_size)
{
    sfud_err result = SFUD_SUCCESS;

    /**
     * add your qspi read flash data code
     */

    return result;
}
#endif /* SFUD_USING_QSPI */

/* about 100 microsecond delay */
static void retry_delay_100us(void) {
    uint32_t delay = 120;
    while(delay--);
}

sfud_err sfud_spi_port_init(sfud_flash* flash)
{
    sfud_err result = SFUD_SUCCESS; // 保留变量，后续可扩展错误处理
    switch (flash->index) {
    case SFUD_GD25Q128E_DEVICE_INDEX: {
        /* RCC 初始化 */
        rcc_configuration(&spi1);
        /* GPIO 初始化 */
        gpio_configuration(&spi1);
        /* SPI 外设初始化 */
        spi_configuration(&spi1);
        /* 同步 Flash 移植所需的接口及数据 */
        flash->spi.wr = spi_write_read;
        flash->spi.lock = spi_lock;
        flash->spi.unlock = spi_unlock;
        flash->spi.user_data = &spi1;
        /* about 100 microsecond delay */
        flash->retry.delay = retry_delay_100us;
        /* adout 60 seconds timeout */
        flash->retry.times = 60 * 10000;
        break;
    }
    default:
        // 未匹配到Flash设备，返回"未找到"错误
        result = SFUD_ERR_NOT_FOUND;
        break;
    }
    return result;
}

/**
 * This function is print debug info.
 *
 * @param file the file which has call this function
 * @param line the line number which has call this function
 * @param format output format
 * @param ... args
 */
void sfud_log_debug(const char* file, const long line, const char* format, ...)
{
    va_list args;

    /* args point to the first variable parameter */
    va_start(args, format);
    printf("[SFUD](%s:%ld) ", file, line);
    /* must use vprintf to print */
    vsnprintf(log_buf, sizeof(log_buf), format, args);
    printf("%s\r\n", log_buf);
    va_end(args);
}

/**
 * This function is print routine info.
 *
 * @param format output format
 * @param ... args
 */
void sfud_log_info(const char* format, ...)
{
    va_list args;

    /* args point to the first variable parameter */
    va_start(args, format);
    printf("[SFUD]");
    /* must use vprintf to print */
    vsnprintf(log_buf, sizeof(log_buf), format, args);
    printf("%s\r\n", log_buf);
    va_end(args);
}
// SUFD 测试
#if 0
#define SFUD_DEMO_TEST_BUFFER_SIZE                     1024
static uint8_t sfud_demo_test_buf[SFUD_DEMO_TEST_BUFFER_SIZE];
static void sfud_demo(uint32_t addr, size_t size, uint8_t *data);
void sfud_test(void){
    if (sfud_init() == SFUD_SUCCESS) {
        sfud_demo(0, sizeof(sfud_demo_test_buf), sfud_demo_test_buf);
    }
}

/**
 * SFUD demo for the first flash device test.
 *
 * @param addr flash start address
 * @param size test flash size
 * @param size test flash data buffer
 */
static void sfud_demo(uint32_t addr, size_t size, uint8_t *data) {
    sfud_err result = SFUD_SUCCESS;
    const sfud_flash *flash = sfud_get_device_table() + 0;
    size_t i;
    /* prepare write data */
    for (i = 0; i < size; i++) {
        data[i] = i;
    }
    /* erase test */
    result = sfud_erase(flash, addr, size);
    if (result == SFUD_SUCCESS) {
        printf("Erase the %s flash data finish. Start from 0x%08X, size is %d.\r\n", flash->name, addr,size);
    } else {
        printf("Erase the %s flash data failed.\r\n", flash->name);
        return;
    }
    /* write test */
    result = sfud_write(flash, addr, size, data);
    if (result == SFUD_SUCCESS) {
        printf("Write the %s flash data finish. Start from 0x%08X, size is %d.\r\n", flash->name, addr,size);
    } else {
        printf("Write the %s flash data failed.\r\n", flash->name);
        return;
    }
    /* read test */
    result = sfud_read(flash, addr, size, data);
    if (result == SFUD_SUCCESS) {
        printf("Read the %s flash data success. Start from 0x%08X, size is %d. The data is:\r\n", flash->name, addr,size);
        printf("Offset (h) 00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F\r\n");
        for (i = 0; i < size; i++) {
            if (i % 16 == 0) {
                printf("[%08X] ", addr + i);
            }
            printf("%02X ", data[i]);
            if (((i + 1) % 16 == 0) || i == size - 1) {
                printf("\r\n");
            }
        }
        printf("\r\n");
    } else {
        printf("Read the %s flash data failed.\r\n", flash->name);
    }
    /* data check */
    for (i = 0; i < size; i++) {
        if (data[i] != i % 256) {
            printf("Read and check write data has an error. Write the %s flash data failed.\r\n", flash->name);
			break;
        }
    }
    if (i == size) {
        printf("The %s flash test is success.\r\n", flash->name);
    }
}

#endif




